<?php

/**
 * Description of DynamicElements
 *
 * @author Kam
 */
class My_Form_Element_DynamicElements extends Zend_Form_Element_Xhtml
{
    /**
     * Default form view helper to use for rendering
     * @var string
     */
    public $helper = 'formDynamicElements';
    
    private $selector;
    private $dynamicRules;
    
    function __construct($selector, $dynamicRules) {
        parent::__construct('de_' . uniqid());
        $this->selector = $selector;
        $this->dynamicRules = $dynamicRules;
    }

    
    public function render(Zend_View_Interface $view = null) {
        $selectorId = $this->selector->getId();
        $rules = array();
        foreach ($this->dynamicRules as $key => $vals) {
            $tmp = array();
            foreach ($vals as $val) {
                $tmp[] = $val->getId();
            }
            $rules[$key] = $tmp;
        }
        $this->setView($view);
        $view = $this->getView();
        $view->headScript()->captureStart();
        ?>
$(function() {
    $('#<?= $selectorId ?>').on('change', function() {
        var val = $(this).val();
        changeVisible(val);
    });
    function changeVisible(val) {
        <?php foreach ($rules as $key => $vals): ?>
            <?php foreach($vals as $eid): ?>
                $('.row-<?= $eid?>').hide();
            <?php endforeach; ?>
        <?php endforeach; ?>
        switch(val) {
            <?php foreach ($rules as $key => $vals): ?>
            case '<?= $key ?>':
                <?php foreach($vals as $eid): ?>
                    $('.row-<?= $eid?>').show();
                <?php endforeach; ?>
                break;
            <?php endforeach; ?>
        }
    }
    changeVisible('');
});
        <?php
        $view->headScript()->captureEnd();
        return '';
    }
}
